<template>
  <div class="app-container-box">
    <div class="box-tag" />
    <span class="title-text">轮播图管理</span>
    <div class="warp-line-top" />
    <div class="btn-box">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" icon="el-icon-refresh" :loading="isLoading" @click="handleRefresh" />
    </div>

    <div class="el-form-box">

      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        height="654"
        :header-cell-style="elTableHeaderStyle"
        :cell-style="elTableCellStyle"
        tooltip-effect="dark"
      >

        <el-table-column prop="index" label="排序" align="center" min-width="20" show-overflow-tooltip />

        <el-table-column prop="MobileImage" label="移动端图片" align="center" min-width="90" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="column-img">
              <img :src="row.MobileImage">
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="PCImage" label="电脑端图片" align="center" min-width="90"><template
          #default="{ row }"
        >
          <div class="column-img">
            <img :src="row.PCImage">
          </div>
        </template>
        </el-table-column>

        <el-table-column prop="RedirectURL" label="跳转路径" align="center" min-width="50">
          <template #default="{ row }">
            <a :href="row.RedirectURL" target="_blank">{{ row.RedirectURL }}</a>
          </template>
        </el-table-column>

        <el-table-column prop="describe" label="描述" align="center" min-width="30" />

        <!-- <el-table-column prop="deleted" :formatter="(row) => (row.deleted ? '启用' : '停用')" label="是否停用" align="center"
          min-width="30" /> -->

        <el-table-column min-width="60" label="操作" align="center">
          <template #default="{ row }">
            <el-button @click="handleEdit(row.id)">修改</el-button>
            <el-button type="danger" :loading="isDeleteLoading" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="添加轮播图" :visible.sync="dialogFormVisible">

        <el-form :model="form" label-position="right" label-width="100px">

          <el-form-item label="移动端图片">
            <el-upload
              class="avatar-uploader"
              :action="fileUploadAddr"
              :show-file-list="false"
              :on-success="handleLogoImageSuccess.bind(this, 'MobileImage')"
              :before-upload="beforeAvatarUpload"
              :headers="fileUploadHeaders"
              :disabled="false"
            >
              <i v-if="!form.MobileImage" class="el-icon-plus" />
              <img v-else :src="form.MobileImage">
            </el-upload>
          </el-form-item>

          <el-form-item label="电脑端图片">
            <el-upload
              class="avatar-uploader"
              :action="fileUploadAddr"
              :show-file-list="false"
              :on-success="handleLogoImageSuccess.bind(this, 'PCImage')"
              :before-upload="beforeAvatarUpload"
              :headers="fileUploadHeaders"
              :disabled="false"
            >
              <i v-if="!form.PCImage" class="el-icon-plus" />
              <img v-else :src="form.PCImage">
            </el-upload>
          </el-form-item>

          <el-form-item label="排序">
            <el-input v-model="form.index" type="number" />
          </el-form-item>

          <el-form-item label="描述">
            <el-input v-model="form.describe" type="textarea" />
          </el-form-item>

          <el-form-item label="跳转链接">
            <el-input v-model="form.RedirectURL" />
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveSubmit">确 定</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getMainRound, delMainRound } from '@/api/lives'
import * as api from '@/api/lives'

export default {
  data() {
    return {
      form: {},
      // 文件上传地址
      fileUploadAddr: '',
      fileUploadHeaders: {
        Authorization: ''
      },
      dialogFormVisible: false,
      submitLoading: false,
      isLoading: false,
      isDeleteLoading: false,
      tableData: []
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  watch: {
    token(n, o) {
      this.fileUploadHeaders.Authorization = n
    }
  },
  async mounted() {
    // token
    this.fileUploadHeaders.Authorization = this.token
    // 上传文件地址
    this.fileUploadAddr = process.env.VUE_APP_BASE_API + '/api/v1/files'

    this.handleRefresh()
  },
  methods: {
    elTableHeaderStyle() {
      return {
        background: '#F0F1F2',
        font_size: '18px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#6D7A8E'
      }
    },
    elTableCellStyle() {
      return {
        font_size: '20px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#8B9DBA'
      }
    },
    async handleRefresh() {
      this.isLoading = true
      try {
        const res = await getMainRound()
        this.tableData = res.data
      } catch (error) {
        console.error(error)
      } finally {
        setTimeout(() => {
          this.isLoading = false
        }, 500)
      }
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    async handleEdit(id) {
      const res = await getMainRound(id)
      this.dialogFormVisible = true
      this.form = res.data
    },

    async handleSaveSubmit() {
      const self = this
      try {
        const API = self.form.id ? 'updateMainRound' : 'addMainRound'
        self.form.PCImage = self.form.PCImage.split('http://static.hljpckj.com/')[1]
        self.form.MobileImage = self.form.MobileImage.split(
          'http://static.hljpckj.com/'
        )[1]

        await api[API](self.form)
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.form = {}
        self.handleRefresh()
      } catch (error) {
        this.$message({
          type: 'error',
          message: '操作失败'
        })
        console.error(error)
      } finally {
        self.dialogFormVisible = false
      }
    },
    handleDelete(id) {
      if (!id) return
      const self = this
      this.$alert('确定删除该轮播图？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        callback: async(action) => {
          if (action === 'confirm') {
            try {
              await delMainRound(id)
              self.handleRefresh()
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            } catch (error) {
              console.error(error)
              this.$message({
                type: 'error',
                message: '删除失败'
              })
            }
          }
        }
      })
    },
    handleLogoImageSuccess(key, res, file) {
      if (res.code === 200) {
        this.$set(this.form, key, res.data[0]?.AccessAddress || '')
      }
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // return isJPG && isLt2M
      return isLt2M
    },
    updateLiveReq() { }
  }
}
</script>

<style lang="scss" scoped>
.app-container-box {
  height: 900px;
}

.box-tag {
  width: 4px;
  height: 28px;
  background: #2e9bea;
  border-radius: 2px;
  position: relative;
  top: 32px;
}

.title-text {
  width: 171px;
  height: 23px;
  font-size: 24px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #4a5462;
  top: 31px;
  left: 54px;
  position: absolute;
}

.el-input-box {
  margin: 0px;
}

::v-deep .el-upload {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  font-size: 28px;
  line-height: 178px;
}

span {
  width: 86px;
  height: 20px;
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #6d7a8e;
}

.submit-change {
  width: 159px;
  height: 50px;
  background: #2e9bea;
  border-radius: 10px;
  position: absolute;
  top: 750px;
  left: 659px;

  ::v-deep {
    span {
      width: 46px;
      height: 20px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
    }
  }
}

.warp-line-top {
  width: 1627px;
  height: 4px;
  background: #edf5fb;
  top: 90px;
  position: absolute;
}

.el-form-box {
  position: absolute;
  top: 176px;
  left: 55px;
  width: 1518px;
  height: 654px;

  ::v-deep .el-form-item__label {
    font-weight: 400;
    font-size: 16px;
    display: #6d7a8e;
  }

  img {
    width: 100%;
    height: 100%;
  }
}

.column-img {
  width: 100%;
  height: 100px;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.btn-box {
  position: absolute;
  display: flex;
  align-items: center;
  width: 100%;
  top: 114px;
  left: 54px;
}

img {
  width: 100%;
  height: auto;
}
</style>
